<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <div style="background: #fff; padding: 13px 15px;">
            <span :class="[state.order_type == '' ? 'btn btn-info' : 'btn']" @click="changeType('')">{{ t('全部') }}</span>
            <span :class="[state.order_type == '出口' ? 'btn btn-info ml-12' : 'btn ml-12']" @click="changeType('出口')">{{ t('出口') }}</span>
            <span :class="[state.order_type == '进口' ? 'btn btn-info ml-12' : 'btn ml-12']" @click="changeType('进口')">{{ t('进口') }}</span>
            <span :class="[state.order_type == '内销' ? 'btn btn-info ml-12' : 'btn ml-12']" @click="changeType('内销')">{{ t('内销') }}</span>
        </div>

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader :buttons="['add', 'quickSearch']" :quick-search-placeholder="t('搜索')">
            <slot name="btnBefore">
                <span class="btn btn-info ml-12" @click="showBatch">{{ t('批量下单') }}</span>
                <span :class="[baTable.table.selection!.length > 0 ? 'btn ml-12' : 'btn ml-12 disabled']" @click="download">{{ t('资料下载') }}</span>
            </slot>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        
        <Table ref="tableRef">
            
            <template #status>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('操作')" align="center" width="150" class-name="business-name" height="200">
                    <template #default="scope">
                        <div v-if="scope.row.user_id > 0">
                            <div>
                                <div class="btn ml-0 mt-0" @click="add(scope)">{{ t('添加') }}</div>
                            </div>
                            
                            <div :class="[scope.row.status.includes('1') ? 'btn btn-info ml-0 mt-5' : 'btn ml-0 mt-5']" @click="setStatus(scope.row.id, 1, scope.row)">{{ t('成交') }}</div>
                            <div :class="[scope.row.status.includes('0') ? 'btn btn-info mt-5 ml-5' : 'btn mt-5 ml-5']" @click="setStatus(scope.row.id, 0, scope.row)">{{ t('终止') }}</div>
                            <div class="btn ml-0 mt-5" @click="edit(scope)">{{ t('编辑') }}</div>
                            <el-popconfirm :title="t('确定要删除这条数据吗') + '?'" @confirm="del(scope)">
                                <template #reference>
                                    <div class="btn ml-5 mt-5">{{ t('删除') }}</div>
                                </template>
                            </el-popconfirm>
                        </div>
                        <div v-if="scope.row.user_id == 0">
                            <div class="btn ml-0 mt-0" @click="add(scope)">{{ t('添加') }}</div>
                            <div v-if="scope.row.user_id == 0" :class="[scope.row.status.includes('1') ? 'btn btn-info mt-0 ml-5' : 'btn mt-0 ml-5']" @click="setStatus(scope.row.id, 1, scope.row)">{{ t('完成') }}</div>
                            <div class="btn ml-0 mt-5" @click="edit(scope)">{{ t('编辑') }}</div>
                            <el-popconfirm :title="t('确定要删除这条数据吗')" @confirm="del(scope)">
                                <template #reference>
                                    <div class="btn ml-5 mt-5">{{ t('删除') }}</div>
                                </template>
                            </el-popconfirm>
                        </div>
                    </template>
                </el-table-column>
            </template>
            <template #files>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('附加文件')" align="center" min-width="120">
                    <template #default="scope">
                        <div style="height: 120px; overflow: auto;">
                            <el-link :href="item.url" target="_blank" class="tag" style="margin-top: 5px;" v-for="(item, index) in scope.row.files" :key="index">{{ item.name }}</el-link>
                        </div>
                    </template>
                </el-table-column>
            </template>

            <template #out-trade-no>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('订单号')" align="center" width="130">
                    <template #default="scope">
                        <el-link @click="router.push({path: '/system/customer_order/detail', query: {id: scope.row.id}})" style="font-size: 13px;" class="contract">
                            <span style="display: block;" v-if="!scope.row.contract">{{ scope.row.out_trade_no }}</span>
                            <span style="display: block;">{{ scope.row.contract }}</span>
                        </el-link>
                    </template>
                </el-table-column>
            </template>

            <template #customer_supplier>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('订单类型') + ' & ' + t('客户名') + ' & ' + t('供货商')" align="center" width="220">
                    <template #default="scope">
                        <div>{{ t(scope.row.order_type) }} / {{ t(scope.row.trade_type) }}</div>
                        <span style="display: block;">{{ scope.row.customer.corp_name_ko }}</span>
                        <span style="display: block;">{{ scope.row.supplier.corp_name_cn }}</span>
                    </template>
                </el-table-column>
            </template>

            <template #trade_type>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('订单号') + ' & ' + t('资料')" align="center" width="120">
                    <template #default="scope">
                        <el-link @click="router.push({path: '/system/customer_order/detail', query: {id: scope.row.id}})" style="font-size: 13px;" class="contract">
                            <span style="display: block;" v-if="!scope.row.contract">{{ scope.row.out_trade_no }}</span>
                            <span style="display: block;">{{ scope.row.contract }}</span>
                        </el-link>
                        <div class="btn btn-mini" style="margin-top: 5px;" @click="openInformation(scope.row)">{{ t('资料管理') }}</div>
                    </template>
                </el-table-column>
            </template>
            
            <template #order_type>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column :label="t('订单状态')" align="center" width="100">
                    <template #default="scope">
                        <div style="">
                            <el-dropdown>
                                <span class="el-dropdown-link" style="cursor: pointer;">
                                    <el-text v-if="scope.row.status == 0" type="danger" style="font-size: 13px;">{{ t('准备下单') }}</el-text>
                                    <el-text v-if="scope.row.status == 1" type="primary" style="font-size: 13px;">{{ t('已确认') }}</el-text>
                                    <el-text v-if="scope.row.status == 2" type="success" style="font-size: 13px;">{{ t('已发货') }}</el-text>
                                </span>
                                <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="changeStatus(scope, 0)" :disabled="scope.row.status == 0"><span style="border-radius: 1.5px; background: #f56c6c; width: 5px; height: 15px; margin-right: 12px;"></span>{{ t('准备下单') }}</el-dropdown-item>
                                    <el-dropdown-item @click="changeStatus(scope, 1)" :disabled="scope.row.status == 1"><span style="border-radius: 1.5px; background: #409eff; width: 5px; height: 15px; margin-right: 12px;"></span>{{ t('已确认') }}</el-dropdown-item>
                                    <el-dropdown-item @click="changeStatus(scope, 2)" :disabled="scope.row.status == 2"><span style="border-radius: 1.5px; background: #67c23a; width: 5px; height: 15px; margin-right: 12px;"></span>{{ t('已发货') }}</el-dropdown-item>
                                </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表单 -->
        <PopupForm />
        <!-- <Batch v-if="batch.show == true" :data="batch" @closeBatch="closeBatch" /> -->
        <Batch />
        <Download />

        <!-- <Quotation v-if="quotation.id != 0" :data="quotation" @closeViewQuotation="closeViewQuotation" /> -->
        <el-drawer
            v-model="state.information.drawer"
            size="1190"
            direction="ltr"
            class="information"
            :close-on-click-modal="true"
            :show-close="true"
            
        >

            <template #title>
                
                <div class="tag">
                    <span style="color: #333; font-size: 14px; font-weight: bold;">
                        {{ current_customer.name }}({{ current_customer.order_type }} / {{ current_customer.trade_type }})
                        
                    </span>
                </div>
                
            </template>
        
            <div id="information" v-loading="state.getFileLoading">

                <div class="tag" style="margin-bottom: 20px;">
                    <span :class="[state.information.tag == 0 ? 'btn active btn-info' : 'btn']" @click="state.information.tag = 0">{{ t('文件资料') }}</span>
                    <span :class="[state.information.tag == 1 ? 'btn active btn-info ml-12' : 'btn ml-12']" @click="state.information.tag = 1">{{ t('基础信息') }}</span>
                    <span :class="[state.information.tag == 2 ? 'btn active ml-12 btn-info' : 'btn ml-12']" @click="state.information.tag = 2; getGoodsList()">{{ t('商品信息') }}</span>
                </div>

                
                <!-- 文件资料 -->
                <div class="ba-operate-form tag-0" style="padding: 0px 10px 0 10px;" v-if="state.information.tag == 0">

                    <el-table :data="state.information.tableData" style="width: 100%; background-color: transparent;" :span-method="arraySpanMethod" border row-class-name="no-hover" cell-class-name="no-hover">
                        <el-table-column :label="t('分类')" width="130" align="center">
                            <template #default="scope">
                                <span style="text-align: center;">{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('名称')" width="130" align="center">
                            <template #default="scope">
                                <span style="text-align: center;" v-if="scope.row.data[scope.row.key].name">{{ scope.row.data[scope.row.key].name }}</span>
                                <Icon v-if="scope.row.data[scope.row.key] && scope.row.data[scope.row.key].generate" @click="generateFile(scope.row.data[scope.row.key].generate, scope.row.data[scope.row.key].type)" name="el-icon-Download" color="#8595F4" size="18" style="position: relative; top: 5px; cursor: pointer;" />
                                
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('文件')" align="center">
                            <template #default="scope">
                                <div v-for="(item, index) in scope.row.data[scope.row.key].value" :key="index">
                                    <span><el-link :href="item.url" target="_blank" type="primary" style="font-size: 13px;">{{ item.name }}</el-link></span>
                                    <span v-if="item.url">
                                        <el-popconfirm :title="t('确定要删除这个文件吗') + '?'" @confirm="delFile(scope.row.data[scope.row.key], scope.row.data[scope.row.key].type, item)">
                                            <template #reference>
                                                <el-link type="danger" style="font-size: 13px; margin-left: 10px;">{{ t('删除') }}</el-link>
                                            </template>
                                        </el-popconfirm>
                                    </span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('上传')" align="center" width="80" class-name="upload-column">
                            <template #default="scope">
                                <FormItem 
                                    :input-attr="{ hideSelectFile: true, onSuccess: uploadFileSuccess(scope.row, scope.row.data[scope.row.key].type), showFileList: false }" 
                                    type="files" v-model="state.file" style="margin-bottom: -13px; margin-top: 0px;"  />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('名称')" width="130" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.data[scope.row.nkey]" style="text-align: center;">{{ scope.row.data[scope.row.nkey].name }}</span>
                                <Icon v-if="scope.row.data[scope.row.nkey] && scope.row.data[scope.row.nkey].generate" @click="generateFile(scope.row.data[scope.row.nkey].generate, scope.row.data[scope.row.nkey].type)" name="el-icon-Download" color="#8595F4" size="18" style="position: relative; top: 5px; cursor: pointer;" />
                            </template>
                        </el-table-column>

                        <el-table-column :label="t('文件')" align="center">
                            <template #default="scope">
                                <div v-if="scope.row.data[scope.row.nkey]">
                                    <div v-for="(item, index) in scope.row.data[scope.row.nkey].value" :key="index">
                                        <span><el-link :href="item.url" target="_blank" type="primary" style="font-size: 13px;">{{ item.name }}</el-link></span>
                                        <span v-if="item.url">
                                            <el-popconfirm :title="t('确定要删除这个文件吗') + '?'" @confirm="delFile(scope.row.data[scope.row.nkey], scope.row.data[scope.row.nkey].type, item)">
                                                <template #reference>
                                                    <el-link type="danger" style="font-size: 13px; margin-left: 10px;">{{ t('删除') }}</el-link>
                                                </template>
                                            </el-popconfirm>
                                        </span>
                                    </div>
                                </div>
                                
                                
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('上传')" align="center" width="80" class-name="upload-column">
                            <template #default="scope">
                                <FormItem 
                                    v-if="scope.row.data[scope.row.nkey]" 
                                    :input-attr="{ hideSelectFile: true, onSuccess: uploadFileSuccess(scope.row, scope.row.data[scope.row.nkey].type), showFileList: false }" 
                                    type="files" 
                                    v-model="state.file" 
                                    style="margin-bottom: -13px; margin-top: 0px;"  
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 基础信息 -->
                <div class="ba-operate-form" style="padding-top: 0;" v-if="state.information.tag == 1">
                    <el-form
                        label-position="right"
                        label-width="110px"
                        :inline="true"
                    >
                        <el-timeline>
                            <el-timeline-item :timestamp="t('境内收发货人信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <FormItem :input-attr="{clearable: true}" required :label="t('企业海关代码')" type="string" v-model="state.information.form.customs_code" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('社会信用代码')" type="string" v-model="state.information.form.creadit_code" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('企业海关名称')" type="string" v-model="state.information.form.customs_name" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('联系电话')" type="string" v-model="state.information.form.cn_tel" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('联系地址')" type="string" v-model="state.information.form.cn_address" />
                                </div>
                            </el-timeline-item>
                            <el-timeline-item :timestamp="t('生产销售单位信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <FormItem :input-attr="{clearable: true}" required :label="t('企业海关代码')" type="string" v-model="state.information.form.product_customs_code" :placeholder="t('')" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('社会信用代码')" type="string" v-model="state.information.form.product_creadit_code" :placeholder="t('')" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('企业海关名称')" type="string" v-model="state.information.form.product_customs_name" :placeholder="t('')" />
                                </div>
                            </el-timeline-item>
                            <el-timeline-item :timestamp="t('境外收发货人信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <FormItem :input-attr="{clearable: true}" required :label="t('买方企业名称')" type="string" v-model="state.information.form.customer_corp_name" :placeholder="t('')" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('买方联系地址')" type="string" v-model="state.information.form.customer_address" :placeholder="t('')" />
                                    <FormItem :input-attr="{clearable: true}" required :label="t('买方联系电话')" type="string" v-model="state.information.form.customer_contact" :placeholder="t('')" />
                                </div>
                            </el-timeline-item>
                            <el-timeline-item :timestamp="t('基础信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <FormItem :input-attr="{clearable: true}" required :label="t('签约地点')" type="string" v-model="state.information.form!.sign_city" :placeholder="t('')" />
                                    <el-form-item required :label="t('包装种类')">
                                        <el-select v-model="state.information.form.pack_type" clearable placeholder=" ">
                                            <el-option v-for="item in state.pack_type" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    
                                    <FormItem :input-attr="{clearable: true}" required :label="t('标记唛码')" type="string" v-model="state.information.form!.make_number" :placeholder="t('')" />
                                    <el-form-item required :label="t('签约日期')">
                                        <el-date-picker v-model="state.information.form.sign_date" value-format="YYYY-MM-DD" type="date" placeholder=" " @change="changeSignDate" />
                                    </el-form-item>
                                    <FormItem required :label="t('发票号')" type="string" v-model="state.information.form!.invoice_number" :placeholder="t('')" />
                                    <FormItem required :label="t('合同协议号')" type="string" v-model="state.information.form!.contract_number" :placeholder="t('')" />
                                </div>
                            </el-timeline-item>
                            <el-timeline-item :timestamp="t('报关信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <el-form-item required :label="t('监管方式')">
                                        <el-select v-model="state.information.form.regulated" clearable placeholder=" ">
                                            <el-option v-for="item in state.regulated" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('征免性质')">
                                        <el-select v-model="state.information.form.exemption" clearable placeholder=" ">
                                            <el-option v-for="item in state.exemption" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('成交方式')">
                                        <el-select v-model="state.information.form.trade_term" clearable placeholder=" ">
                                            <el-option v-for="item in state.trade_term" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('贸易国')">
                                        <el-select v-model="state.information.form.trade_country" clearable placeholder=" ">
                                            <el-option v-for="item in state.trade_country" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('最终目的国')">
                                        <el-select v-model="state.information.form.destination" clearable placeholder=" ">
                                            <el-option v-for="item in state.destination" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('成交币制')">
                                        <el-select v-model="state.information.form.currency" clearable placeholder=" ">
                                            <el-option v-for="item in state.currency" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('是否退税')">
                                        <el-select v-model="state.information.form.is_drawback" clearable placeholder=" ">
                                            <el-option :label="t('是')" value="y" />
                                            <el-option :label="t('否')" value="n" />
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </el-timeline-item>
                            <el-timeline-item :timestamp="t('其他费用信息')" placement="top">
                                <div style="padding-top: 15px;">
                                    <FormItem :input-attr="{clearable: true}" required :label="t('运费')" type="number" v-model="state.information.form.freight_amount" :placeholder="t('')" />
                                    <el-form-item required :label="t('运费币制')">
                                        <el-select v-model="state.information.form.freight_currency" clearable placeholder=" ">
                                            <el-option v-for="item in state.currency" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('运费类型')">
                                        <el-select v-model="state.information.form.freight_type" clearable placeholder=" ">
                                            <el-option :label="t('率')" value="1" />
                                            <el-option :label="t('单价')" value="2" />
                                            <el-option :label="t('总价')" value="3" />
                                        </el-select>
                                    </el-form-item>
                                    <FormItem :input-attr="{clearable: true}" required :label="t('保费')" type="number" v-model="state.information.form.premium_amount" :placeholder="t('')" />
                                    <el-form-item required :label="t('保费币制')">
                                        <el-select v-model="state.information.form.premium_currency" clearable placeholder=" ">
                                            <el-option v-for="item in state.currency" :key="item.code" :label="item.title" :value="item.title" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item required :label="t('保费类型')">
                                        <el-select v-model="state.information.form.premium_type" clearable placeholder=" ">
                                            <el-option :label="t('率')" value="1" />
                                            <el-option :label="t('总价')" value="3" />
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </el-timeline-item>
                        </el-timeline>
                        <div style="text-align: center;">
                            
                        </div>
                        
                        
                    </el-form>
                </div>
                <!-- 商品信息 -->
                <div class="ba-operate-form" style="padding-top: 0px;" v-if="state.information.tag == 2">
                    <el-drawer v-model="state.information.goods_drawer" :title="state.information.goods_drawer_method == 'add' ? t('添加商品') : t('编辑商品')" size="790" direction="rtl" >
                        <div>
                            <el-form
                                label-position="top"
                                label-width="130px"
                                :inline="true"
                            >
                                <el-form-item required label="HS CODE">
                                    <el-select v-model="state.goodsForm.hscode_id" placeholder=" " clearable filterable @change="changeHscode">
                                        <el-option v-for="item in state.hsCode" :key="item.id" :label="item.hscode" :value="item.id">
                                            <span style="margin-right: 20px; color: #333; font-weight: normal;">{{ item.hscode }}</span>
                                            <span style="color: #8a8a8a; font-size: 12px; font-weight: normal;">{{ item.name }}</span>
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <FormItem :input-attr="{clearable: true}" required :label="t('商品名称') + '(' + t('中文') + ')'" type="string" v-model="state.goodsForm.name" :placeholder="t('必须存在中文')" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('商品名称') + '(' + t('英文') + ')'" type="string" v-model="state.goodsForm.name_en" placeholder=" " />
                                <FormItem :input-attr="{clearable: true}" required :label="t('境内货源地')" type="string" v-model="state.goodsForm.cn_origin" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('原产国')" type="string" v-model="state.goodsForm.country_of_origin" />
                                
                                <FormItem :input-attr="{clearable: true}" required :label="t('外包装箱数')" type="string" v-model="state.goodsForm.pack_qty" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('法定数量')" type="string" v-model="state.goodsForm.qty" :placeholder="t('根据法定单位填写')" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('法定单位')" type="string" v-model="state.goodsForm.unit" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('成交数量')" type="string" v-model="state.goodsForm.deal_qty" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('成交单位')" type="string" v-model="state.goodsForm.deal_unit" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('成交总价')" type="string" v-model="state.goodsForm.deal_amount" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('成交单价')" type="string" v-model="state.goodsForm.deal_unit_amount" />
                                
                                
                                <el-form-item required :label="t('混装情况')">
                                    <el-select v-model="state.goodsForm.is_mix" clearable placeholder=" ">
                                        <el-option :label="t('混装')" value="y" />
                                        <el-option :label="t('非混装')" value="n" />
                                    </el-select>
                                </el-form-item>
                                <FormItem :input-attr="{clearable: true}" required :label="t('净重量')" type="string" v-model="state.goodsForm.net_weight" :placeholder="t('不含包装')" />
                                <FormItem :input-attr="{clearable: true}" required :label="t('毛重量')" type="string" v-model="state.goodsForm.gross_weight" :placeholder="t('含包装')" />

                                

                            </el-form>
                            <el-divider content-position="center">{{ t('规格型号信息') }}</el-divider>
                            <el-form label-position="top" label-width="120px">
                                <el-empty v-if="state.hscodeFormData.length == 0" :description="t('暂无规格信息')" />
                                <div v-for="(item, key) in state.hscodeFormData" :key="key">
                                    <FormItem v-model="state.hscodeForm['hscode_sku_' + item.id]" required :label="t(item.title)" :input-attr="{clearable: true}" type="string" />
                                </div>
                                
                            </el-form>
                            
                        </div>
                        <template #footer v-if="state.information.goods_drawer">
                            <div style="margin-right: 55px;">
                                <span class="btn" @click="state.information.goods_drawer = false;">{{ t('取消') }}</span>
                                <span class="btn btn-primary ml-12" @click="saveInformationGoods" v-if="state.information.goods_drawer_method == 'add'">{{ t('保存') }}</span>
                                <span class="btn btn-primary ml-12" @click="updateInformationGoods" v-if="state.information.goods_drawer_method == 'edit'">{{ t('保存') }}</span>
                            </div>
                        </template>
                    </el-drawer>
                    <!-- 商品列表表格 -->
                    <span class="btn" style="margin-bottom: 10px;" @click="addGoods">{{ t('添加商品') }}</span>
                    <el-popover :visible="state.pull.pop" placement="top" :width="260">
                        <div style="margin-bottom: 10px;">
                            <el-input v-model="state.pull.out_trade_no" :placeholder="t('请输入订单号')" clearable />
                        </div>
                        <div style="text-align: right; margin: 0">
                            <el-button size="small" text @click="state.pull.pop = false">{{ t('取消') }}</el-button>
                            <el-button size="small" type="primary" @click="pull">{{ t('确定') }}</el-button>
                        </div>
                        <template #reference>
                            <span class="btn ml-12" @click="state.pull.pop = true" style="margin-bottom: 10px;">{{ t('拉取信息') }}</span>
                        </template>
                    </el-popover>
                    <el-table :data="state.goods" align="center">
                        <el-table-column :label="t('商品编码')">
                            <template #default="scope">
                                <span>{{ scope.row.hscode }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('商品名称')" align="center">
                            <template #default="scope">
                                <span>{{ scope.row.name }}</span>
                                <div v-if="scope.row.name_en">({{ scope.row.name_en }})</div>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('箱数')" align="center">
                            <template #default="scope">
                                <span>{{ scope.row.pack_qty }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('毛重')" align="center">
                            <template #default="scope">
                                <span>{{ scope.row.gross_weight }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('净重')" align="center">
                            <template #default="scope">
                                <span>{{ scope.row.net_weight }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('操作')" align="center">
                            <template #default="scope">
                                <span class="btn btn-primary btn-small" @click="editGoods(scope.row, scope.$index)">{{ t('编辑') }}</span>
                                <el-popconfirm :title="t('确定要删除该条记录吗')" @confirm="delGoods(scope.row, scope.$index)">
                                    <template #reference>
                                        <span class="btn btn-danger ml-5 btn-small">{{ t('删除') }}</span>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <template #footer v-if="state.information.tag == 1">
                <div style="margin-right: 55px;">
                    <span class="btn" @click="state.information.drawer = false;">{{ t('取消') }}</span>
                    <span class="btn btn-primary ml-12" @click="saveInformation">{{ t('保存') }}</span>
                </div>
            </template>
        </el-drawer>
        

    </div>

    
</template>

<script setup lang="ts">
import { ref, provide, onMounted, reactive, markRaw } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import baTableClass from '/@/utils/baTable'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Batch from './batch.vue'
import Download from './download.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import router from '/@/router/index'
import { changeStatusApi, pullApi } from '/@/api/most/customer/order'

import PayAmount from './render/pay_amount.vue';
import Note from './render/note.vue';

import { getGoodsHscodeApi, getHscodeSkuApi, delGoodsApi, getInformationGoodsApi, saveFileApi, getFileApi, saveInformationApi, saveInformationGoodsApi, updateInformationGoodsApi, generatePiNumApi, delFileApi } from '/@/api/most/business/information'

import { generateFileApi } from '/@/api/most/customer/generate'
import FormItem from '/@/components/formItem/index.vue'
defineOptions({
    name: 'customer_order/index',
})

const { t } = useI18n()
const tableRef = ref()

const current_customer = reactive({
    name: '',
    order_type: '',
    trade_type: '',
})



const closeBatch = () => {
    batch.show = false;
}

const state = reactive({
    file: [],
    pull: {
        pop: false,
        out_trade_no: ''
    },
    getFileLoading: false,
    loading: false,
    order_type: '',
    status: 0,
    pack_type: [], // 包装种类列表
    exemption: [], // 征免性质列表
    trade_term: [], // 成交方式
    regulated: [], // 监管方式
    destination: [], // 最终目的国
    trade_country: [], // 贸易国
    currency: [], // 货币
    sub_status: {
        count_1: 0,
        count_2: 0,
        count_3: 0,
        count_4: 0
    },
    hsCode: [],
    goods: [],
    goodsForm: {},
    hscodeFormData: [],
    hscodeForm: {},
    information: {
        no: 0,
        id: 0,
        drawer: false,
        goods_drawer: false,
        goods_drawer_method: 'add',
        tag: 0,
        file: {
            
        },
        form: {
            
        },
        fileData: [],
        tableData: []
    }
    
});

const pull = () => {
    let data = {
        order_id: state.information.form.order_id,
        out_trade_no: state.pull.out_trade_no
    }
    state.pull.pop = false;
    state.pull.out_trade_no = '';
    pullApi(data).then((e) => {
        // getFileFun(data.order_id)
        getGoodsList()
    })
}




const generateFile = (type: string, field: string) => {
    let param = {
        order_id: state.information.form.order_id,
        file: type,
        field: field
    }
    generateFileApi(param).then((e) => {
        // console.log(e);
        // getFileFun(state.information.form.order_id)
        window.open(e.data);
    })
}

/**
 * 保存表单信息
 */
const saveInformation = () => {
    saveInformationApi(state.information.form).then((e) => {
        if(e.code == 1){
            closeInformation();
        }
    })
}

// 保存添加商品表单的信息
const saveInformationGoods = () => {
    state.goodsForm.order_id = state.information.form.order_id;
    let data = {
        goodsForm: state.goodsForm,
        hscodeForm: state.hscodeForm
    }
    saveInformationGoodsApi(data).then((e) => {
        if(e.code == 1){
            state.information.goods_drawer = false;
            getGoodsList()
        }
    })
}

const updateInformationGoods = () => {
    state.goodsForm.order_id = state.information.form.order_id;
    let data = {
        goodsForm: state.goodsForm,
        hscodeForm: state.hscodeForm
    }
    updateInformationGoodsApi(data).then((e) => {
        if(e.code == 1){
            state.information.goods_drawer = false;
            getGoodsList()
        }
    })
}

const editGoods = (row: anyObj, index: number) => {
    state.information.goods_drawer_method = 'edit';
    state.information.goods_drawer = true;
    state.goodsForm.name = row.name;
    state.goodsForm.name_en = row.name_en;
    state.goodsForm.cn_origin = row.cn_origin;
    state.goodsForm.country_of_origin = row.country_of_origin;
    state.goodsForm.unit = row.unit;
    state.goodsForm.qty = row.qty;
    state.goodsForm.deal_qty = row.deal_qty;
    state.goodsForm.deal_unit = row.deal_unit;
    state.goodsForm.deal_amount = row.deal_amount ? row.deal_amount / 100 : null;
    state.goodsForm.deal_unit_amount = row.deal_unit_amount ? row.deal_unit_amount / 100 : null;
    state.goodsForm.is_mix = row.is_mix;
    state.goodsForm.pack_qty = row.pack_qty;
    state.goodsForm.net_weight = row.net_weight;
    state.goodsForm.gross_weight = row.gross_weight;
    state.goodsForm.hscode_id = row.hscode_id;
    state.goodsForm.id = row.id;
    getGoodsHscodeApi({id: row.id}).then((e) => {
        state.hscodeFormData = e.data.hscode_sku;
        // state.hscodeForm = e.data;
        state.hscodeFormData.forEach(function(item, index) {
            let keyName = 'hscode_sku_' + item.id;

            state.hscodeForm[keyName] = e.data.goods_sku.hasOwnProperty(keyName) ? e.data.goods_sku[keyName] : '';
        });
    })
}

const delGoods = (row: anyObj, index: number) => {
    delGoodsApi({id: row.id}).then((e) => {
        state.goods = e.data.goods;
    })
}

// 选择签约日期
const changeSignDate = () => {
    let val = state.information.form.sign_date;
    if(val != undefined && val != '' && val != null){
        generatePiNumApi({date: val, order_id: state.information.form.order_id}).then((e) => {
            state.information.form.invoice_number = e.data;
            state.information.form.contract_number = e.data;
        })
    }else{
        state.information.form.invoice_number = null;
        state.information.form.contract_number = null;
    }
    
}

/**
 * 选择商品编码时触发
 */
const changeHscode = ( value ) => {
    getHscodeSkuApi({id: value}).then((e) => {
        state.hscodeFormData = e.data;
        // state.hscodeForm = e.data;
        state.hscodeFormData.forEach(function(item, index) {
            let keyName = 'hscode_sku_' + item.id;
            state.hscodeForm[keyName] = '';
        });
    })
}

// .data[scope.row.nkey]
const uploadFileSuccess = (row: anyObj, type: string) => {
    return (file: anyObj) => {
        console.log(file)
        // if(row.type == 'buy_contract') state.file.buy_contract = row.file_url
        // row.file = row.file_url;
        let data = {
            order_id: state.information.form.order_id,
            file_url: state.file,
            type: type
        }
        saveFileApi(data).then((e) => {
            // row.value = e.data;
            state.file = [];
            getFileFun(state.information.form.order_id)
        })
        
    }
}

const delFile = (row: anyObj, type: string, item: anyObj) => {
    delFileApi({order_id: state.information.form.order_id, type: type, file_id: item.id}).then((e) => {
        // row.value = e.data;
        getFileFun(state.information.form.order_id)
    })
}

const addGoods = () => {
    state.goodsForm = {}; 
    state.hscodeFormData = {};
    state.hscodeForm = {};
    state.information.goods_drawer_method = 'add'; 
    state.information.goods_drawer = true;
}

// 合并单元格
const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}: SpanMethodProps) => {
    if (columnIndex === 0) {
        if (row.num != undefined) {
            return {
                rowspan: row.num,
                colspan: 1,
            }
        } else {
            return {
                rowspan: 0,
                colspan: 0,
            }
        }
    }
}


const openInformation = (row: anyObj) => {

    current_customer.name = row.customer.corp_name_ko;
    current_customer.order_type = t(row.order_type);
    current_customer.trade_type = t(row.trade_type);

    state.information.drawer = true;
    state.information.tag = 0;
    state.information.form = {};
    state.information.form.order_id = row.id;

    state.information.tableData = [];
    state.information.fileData = [];

    getFileFun(row.id)
}

const getFileFun = (order_id: number) => {
    state.getFileLoading = true;
    getFileApi({order_id: order_id}).then((e) => {
        state.getFileLoading = false;
        state.information.tableData.forEach(item => {
            if(item.type == 'customer_contract') item.file = e.data.file.customer_contract;
            if(item.type == 'customer_bjd') item.file = e.data.file.customer_bjd;
            if(item.type == 'customer_invoice') item.file = e.data.file.customer_invoice;
            if(item.type == 'sell_contract') item.file = e.data.file.sell_contract;
            if(item.type == 'sell_po') item.file = e.data.file.sell_po;
            if(item.type == 'sell_pi') item.file = e.data.file.sell_pi;
            if(item.type == 'wl_dcd') item.file = e.data.file.wl_dcd;
            if(item.type == 'wl_xd') item.file = e.data.file.wl_xd;
            if(item.type == 'wl_bgd') item.file = e.data.file.wl_bgd;
            if(item.type == 'wl_yf') item.file = e.data.file.wl_yf;
            if(item.type == 'wl_fp') item.file = e.data.file.wl_fp;
            if(item.type == 'sw_sfd') item.file = e.data.file.sw_sfd;
        });
        if(e.data.customer != null){
            state.information.form.customer_corp_name = e.data.customer.corp_name_ko;
            state.information.form.customer_address = e.data.customer.address;
            state.information.form.customer_contact = e.data.customer.contact;
        }
        
        state.information.form.customs_code = e.data.cn.customs_code;
        state.information.form.creadit_code = e.data.cn.creadit_code;
        state.information.form.customs_name = e.data.cn.customs_name;
        state.information.form.cn_tel = e.data.cn.tel;
        state.information.form.cn_address = e.data.cn.address;

        state.information.form.product_customs_code = e.data.product.product_customs_code;
        state.information.form.product_creadit_code = e.data.product.product_creadit_code;
        state.information.form.product_customs_name = e.data.product.product_customs_name;

        state.pack_type = e.data.pack_type;
        state.regulated = e.data.regulated;
        state.exemption = e.data.exemption;
        state.trade_term = e.data.trade_term;
        state.destination = e.data.destination;
        state.trade_country = e.data.trade_country;
        state.currency = e.data.currency;

        state.information.form.sign_date = e.data.otherInfo.sign_date;
        state.information.form.invoice_number = e.data.otherInfo.invoice_number;
        state.information.form.contract_number = e.data.otherInfo.contract_number;

        
        state.information.form.sign_city = e.data.otherInfo.sign_city;
        state.information.form.pack_type = e.data.otherInfo.pack_type;
        state.information.form.make_number = e.data.otherInfo.make_number;

        
        state.information.form.regulated = e.data.otherInfo.regulated;
        state.information.form.exemption = e.data.otherInfo.exemption;
        state.information.form.trade_term = e.data.otherInfo.trade_term;
        state.information.form.trade_country = e.data.otherInfo.trade_country;
        state.information.form.destination = e.data.otherInfo.destination;
        state.information.form.currency = e.data.otherInfo.currency;
        state.information.form.is_drawback = e.data.otherInfo.is_drawback;
        state.information.form.freight_amount = e.data.otherInfo.freight_amount;
        state.information.form.freight_currency = e.data.otherInfo.freight_currency;
        state.information.form.freight_type = e.data.otherInfo.freight_type;
        state.information.form.premium_amount = e.data.otherInfo.premium_amount;
        state.information.form.premium_currency = e.data.otherInfo.premium_currency;
        state.information.form.premium_type = e.data.otherInfo.premium_type;

        
        state.hsCode = e.data.hsCode;

        state.information.tableData = e.data.fileData;
        
    })
}

const getGoodsList = () => {
    state.goods = [];
    getInformationGoodsApi({order_id: state.information.form.order_id}).then((e) => {
        state.goods = e.data.goods;
    })
}

const closeInformation = () => {
    state.information.form = {};
    state.information.drawer = false;
}








const changeStatus = (scope: anyObj, status: number) => {
    
    // scope.row.status = status;
    changeStatusApi({id: scope.row.id, status: status}).then((e) => {
        if(e.code == 1){
            scope.row.status = status;
        }
    })
}

const edit = (scope: anyObj) => {
    baTable.onTableAction('edit', scope)
}

const add = (scope: anyObj) => {
    baTable.form.operate = 'AddProcess'
    baTable.form.items!.id = scope.row.id
    baTable.form.items!.name = scope.row.name
}

const del = (scope: anyObj) => {
    baTable.onTableAction('delete', scope)
}



/**
 * 切换类型
 */
const changeType = (type: string) => {
    state.order_type = type;
    baTable.table.filter!.order_type = type;
    baTable.getIndex();
}


/**
 * 设置状态 
 */
const setStatus = (id: number, status: number, row: anyObj) => {
    let data = {id: id, status: status}
    setStatusApi(data).then((e) => {
        row.status = e.data.status;
        state.sub_status = e.data.sum_status
    })
}


let optButtons = defaultOptButtons([])


// 自定义一个新的按钮
let newButton: OptButton[] = [
    {
        render: 'basicButton', // 渲染方式:tipButton=带tip的按钮,confirmButton=带确认框的按钮,moveButton=移动按钮
        name: 'edit',
        title: 'edit',
        text: t('编辑'),
        type: 'primary',
        class: 'btn btn-primary btn-small btn-sm ml-0 mt-5',
        icon: '',
    },{
        render: 'confirmButton',
        name: 'delete',
        title: '',
        text: t('删除'),
        type: 'danger',
        class: 'btn btn-danger ml--6 mt-5 btn-small',
        icon: '',
        popconfirm: {
            confirmButtonText: t('删除'),
            cancelButtonText: t('取消'),
            confirmButtonType: 'danger',
            title: t('确定要删除这条数据吗') + '?',
        }
    }
]

// 新按钮合入到默认的按钮数组
optButtons = newButton.concat(optButtons)

// const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])

// 创建一个新的 Date 对象来获取当前日期
const currentDate = new Date();

// 获取年、月和日
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始计数，所以要加 1
const day = String(currentDate.getDate()).padStart(2, '0');

// 组合成 YYYY-MM-DD 格式的日期字符串
const formattedDate = `${year}-${month}-${day}`;

const showBatch = () => {
    baTable.form.items!.create_time = formattedDate;
    baTable.form.operate = 'Batch'
}


const download = () => {

    if(baTable.table.selection!.length <= 0) return;

    baTable.form.items!.ids = baTable.table.selection;

    baTable.form.operate = 'Download'


}

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/system/customer.Order/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { 
                label: t('类型'), 
                prop: 'trade_type', 
                align: 'center', 
                operatorPlaceholder: t('Fuzzy query'), 
                operator: 'LIKE', 
                sortable: false,
                render: 'slot',
                slotName: 'trade_type'
            },
            // { label: t('订单号'), width: '165', prop: 'out_trade_no', align: 'center', render: 'slot', slotName: 'out-trade-no' },
            { label: t('客户名'), prop: 'customer.corp_name_ko', align: 'center', render: 'slot', slotName: 'customer_supplier' },
            { label: t('订单总价'), prop: 'amount_text', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { 
                label: t('付款金额'), 
                prop: 'pay_amount_text', 
                align: 'center', 
                operatorPlaceholder: t('Fuzzy query'), 
                operator: 'LIKE', 
                sortable: false,
                render: 'customRender', 
                customRender: markRaw(PayAmount),
            },
            { 
                label: t('订单状态'), 
                prop: 'order_type', 
                align: 'center', 
                operatorPlaceholder: t('Fuzzy query'), 
                operator: 'LIKE', 
                sortable: false,
                render: 'slot',
                slotName: 'order_type'
            },
            // { label: t('相关资料'), prop: 'order_type', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { 
                label: t('备注'), prop: 'note', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false,
                width: 250,
                render: 'customRender', 
                customRender: markRaw(Note),
            },
            { label: t('下单时间'), prop: 'create_time', align: 'center', render: 'datetime', timeFormat: 'yy-mm-dd' },
            { label: t('操作'), align: 'center', render: 'buttons', buttons: optButtons, operator: false, width: 100 },
        ],
        dblClickNotEditColumn: ['all'],
        defaultOrder: { prop: 'id', order: 'desc' },
    },
    {
        defaultItems: { create_time: formattedDate },
        

    },{
        
    },{
        getIndex: ({ res }: { res: ApiResponse }) => { // 查看后
            state.sub_status = res.data.sum_status;
            // console.log(res.data);
            // console.log(state.sub_status)
        },
        onSubmit: ({ res }: { res: ApiResponse }) => {
            if(res.data.type == 'download'){
                window.open(res.data.file_url)
            }
        }
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">

:deep(.el-image){
    // width: 60px;
    // height: 60px;
    width: unset;
    height: unset;
    // max-height: 100px;
    // max-width: 80px;
    // max-height: 80px;
}
:deep(td.business-name > div.cell) {
    min-height: 80px;
    display:flex;
    justify-content:center; 
    align-items:center;
}
.tian{
    cursor: pointer;
}
.tian:hover{
    color: #409EFF;
}

:deep(.el-image > img){
    // width: 60px;
    // height: 60px;
    width: unset;
    height: unset;
    // max-height: 100px;
    max-width: 80px;
    max-height: 80px;
}
:deep(.ba-data-table .btn){
    padding: 4px 14px;
}


:deep(.ba-data-table .margin-left-none:last-child){
    margin-bottom: 0px;
}
:deep(.table-operate-text){
    padding-left: 0;
}
:deep(.font-size-13){
    font-size: 13px;
}
:deep(.pay-type .el-radio){
    margin-right: 10px;
}
pre{
    font-family: 'Helvetica Neue',Helvetica,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','微软雅黑',Arial,sans-serif;
}
:deep(.ba-operate-dialog .el-dialog__body){
    padding-bottom: 0;
    padding-left: 0;
    padding-right: 0;
}
:deep(.quotation-scrollbar .el-scrollbar:first-child > .el-scrollbar__wrap){
    height: 100%;
}
:deep(.ml-0){
    margin-left: 0!important;
}
:deep(.mt-8){
    margin-top: 8px;
}
:deep(.ml--6){
    margin-left: -6px;
}
:deep(.ml-5){
    margin-left: 5px;
}
:deep(.mt-5){
    margin-top: 5px;
}
:deep(.el-button){
    height: unset;
}
:deep(.el-table__row.no-hover:hover .no-hover) {
  background-color: transparent!important; /* 使用 !important 来确保覆盖默认样式 */
  color: inherit !important;
//   background-color: red;
}
.tag{
    margin-right: 18px;
}

// .tag .active{
//     background: #ECF5FF;
//     color: #409EFF;
//     border: 1px solid #C6E2FF;
// }
:deep(.information .el-drawer__body){
    padding-top: 0;
}
:deep(.upload-column .el-form-item__label){
    display: none;
}
:deep(.upload-column .ba-upload.file){
    line-height: 8px;
}
:deep(.tag-0 .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf){
    border-top: 2px solid #efefef;
    border-right: 2px solid #efefef;

}

:deep(.information .el-table th.el-table__cell){
    background: rgb(245, 245, 246);
    color: #333;
    border-color: rgb(234, 234, 234);
}
:deep(.information .el-form--inline .el-form-item){
    margin-right: 23px;
}
:deep(.information .el-timeline-item){
    padding-bottom: unset;
}
:deep(.information .el-timeline-item__timestamp){
    font-size: 14px;
}
:deep(.el-button){
    height: unset;
}

:deep(.el-image > img){
    max-width: 50px;
    max-height: 50px;
}
:deep(.el-form--default.el-form--label-top .el-form-item .el-form-item__label){
    margin-bottom: 3px;
}
:deep(.information .el-drawer__header){
    margin-bottom: 17px!important;
}
:deep(.contract .el-link__inner){
    display: block;
}
</style>
